﻿using ArtMath.Control;
using ArtMath.Core.Helper;
using ArtMath.Flag;
using ArtMath.Parameter;
using ArtMath.Resource;
using ArtMath.Setting;
using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows.Forms;
using WeifenLuo.WinFormsUI.Docking;
using ArtMath.CommonType;

namespace ArtMath.Window
{
    public partial class ParametersManagerWindow : DockContent
    {
        [Browsable(false)]
        public SketchPad LinkedPad { get; private set; }
        [Browsable(false)]
        public Document LinkedDocument { get; private set; }
        public ParametersManagerWindow()
        {
            InitializeComponent();
            splitContainer1.Panel2Collapsed = true;
            ChangeColorTheme(Settings.Instance.ColorTheme);
        }
        public void Document_Activated(Document sender)
        {
            lvParam.Items.Clear();
            LinkedDocument = sender;
            if (LinkedDocument == null)
            {
                //lvParam.Enabled = toolStrip2.Enabled = false;
                Enabled = false;
            }
            else
            {
                foreach (BasicParameter item in LinkedDocument.Parameters)
                {
                    if (item.ObjectState == ObjectState.Normal)
                    {
                        CalculatedParameter cp = item as CalculatedParameter;
                        if (cp == null || Settings.Instance.ShowOtherPadParameters)
                        {
                            lvParam.Items.Add(item.ParametersManagerItem);
                        }
                    }
                }
                //lvParam.Enabled = toolStrip2.Enabled = true;
                Enabled = true;
            }
        }
        public void SketchPad_Activated(SketchPad sender)
        {
            if (Settings.Instance.ShowOtherPadParameters)
            {
                LinkedPad = sender;
            }
            else
            {
                if (LinkedPad != null)
                {
                    foreach (CalculatedParameter item in LinkedPad.Parameters)
                    {
                        if (item.ObjectState == ObjectState.Normal)
                        {
                            item.ParametersManagerItem.Remove();
                        }
                    }
                }
                LinkedPad = sender;
                if (LinkedPad != null)
                {
                    foreach (CalculatedParameter item in LinkedPad.Parameters)
                    {
                        if (item.ObjectState == ObjectState.Normal)
                        {
                            lvParam.Items.Add(item.ParametersManagerItem);
                        }
                    }
                }
            }
        }
        public void ChangeColorTheme(UIColorTheme theme)
        {
            switch (theme)
            {
                case UIColorTheme.Light:
                    EnableVSRenderer(VisualStudioToolStripExtender.VsVersion.Vs2015, vS2015LightTheme1);
                    break;
                case UIColorTheme.Blue:
                    EnableVSRenderer(VisualStudioToolStripExtender.VsVersion.Vs2015, vS2015BlueTheme1);
                    break;
                case UIColorTheme.Dark:
                    EnableVSRenderer(VisualStudioToolStripExtender.VsVersion.Vs2015, vS2015DarkTheme1);
                    break;
            }
        }
        void EnableVSRenderer(VisualStudioToolStripExtender.VsVersion version, ThemeBase theme)
        {
            visualStudioToolStripExtender1.SetStyle(toolStrip2, version, theme);
            visualStudioToolStripExtender1.SetStyle(cmsItem, version, theme);
            visualStudioToolStripExtender1.SetStyle(cmsList, version, theme);
        }
        public ListView ParameterList
        {
            get { return lvParam; }
        }
        private void tsbAdd_Click(object sender, EventArgs e)
        {
            AddParameter();
        }
        public void AddParameter()
        {
            AddParameterWindow ap = new AddParameterWindow(LinkedPad);
            if (ap.ShowDialog() == DialogResult.OK)
            {
                BasicParameter param = null;
                switch (ap.ParamType)
                {
                    case AddParameterWindow.ParameterType.RW:
                        param = new BasicParameter(LinkedDocument, ap.ParameterName, ap.Value, ap.Start, ap.Step, ap.Stop)
                        {
                            Unit = ap.ParameterUnit,
                        };
                        break;
                    case AddParameterWindow.ParameterType.Component:
                        param = new ObjectParameter(LinkedDocument,
                            LinkedPad.StdObjName(ap.ParameterName, false, false), ap.SelectedComponent.Object,
                            ap.SelectedComponent.Properties[ap.SelectedParameterName].Item1.Name, 
                            ap.SelectedComponent.Properties[ap.SelectedParameterName].Item2);
                        break;
                }
                SketchPad_ParameterCreated(LinkedPad, param);
                if (ap.CurrentSketchpadDisplay)
                {
                    param.ShowInPads = LinkedPad.Name;
                }
                LinkedDocument.Modified = true;
            }
        }
        public void SketchPad_ParameterCreated(SketchPad sender, BasicParameter param)
        {
            param.RegisterParameterEvents();
            foreach (ListViewItem item in lvParam.SelectedItems)
            {
                item.Selected = false;
            }
            lvParam.Items.Add(param.ParametersManagerItem);
            param.ParametersManagerItem.Selected = true;
        }
        private void tsbDelete_Click(object sender, EventArgs e)
        {
            DeleteParameters();
        }
        public void DeleteParameters(bool all = false)
        {
            bool sft = Flags.Shift;
            if (sft)
            {
                if (MessageBox.Show(string.Format(Resources.Translate("DeleteObjectAsk"), Resources.Translate("Parameter")), Resources.Translate("Ask"), MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
                {
                    return;
                }
            }
            foreach (ListViewItem item in lvParam.GetItems(all))
            {
                BasicParameter p = item.Tag as BasicParameter;
                try
                {
                    p.Delete(!sft);
                    LinkedDocument.Modified = true;
                }
                catch (Exception)
                {
                    MessageBox.Show(string.Format(Resources.Translate("DeleteUsingParameter"), p.Name), Resources.Translate("Error"), MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            if (lvParam.Items.Count > 0)
            {
                lvParam.Items[0].Selected = true;
            }
        }
        private void lvPara_SelectedIndexChanged(object sender, EventArgs e)
        {
            tsbDelete.Enabled = lvParam.SelectedItems.Count > 0;
            plus.Enabled = minus.Enabled = false;
            if (lvParam.SelectedItems.Count > 0)
            {
                if (LinkedDocument.SelectedPad != null) LinkedDocument.SelectedPad.Layer.SelectNone();
                Text = $"{Resources.JoinLocalizedString("Parameter", "Manager")} - " + (lvParam.SelectedItems.Count == 1 ? lvParam.SelectedItems[0].Text : $"({Resources.JoinLocalizedString("Multiple", "Parameter")})");
                //tscbStep.Text = lvPara.SelectedItems.Count == 1 ? (lvPara.SelectedItems[0].Tag as Parameter).Step.ToString() : "1";
                object[] objs = new object[lvParam.SelectedItems.Count];
                for (int i = 0; i < objs.Length; i++)
                {
                    BasicParameter p = lvParam.SelectedItems[i].Tag as BasicParameter;
                    objs[i] = p;
                    if (p is ReadOnlyParameter)
                    {
                        if (p is TwoStraightLinesArrivalAngleParameter)
                        {
                            tsbResetRound.Enabled = true;
                        }
                    }
                    else
                    {
                        plus.Enabled = minus.Enabled = true;
                    }
                }
                Program.WinProperty.PropertyGrid.SelectedObjects = objs;
                Program.WinProperty.Text = $"{Resources.Translate("Property")} - " + (lvParam.SelectedItems.Count == 1 ? lvParam.SelectedItems[0].Text : $"({Resources.JoinLocalizedString("Multiple", "Parameter")})");
                lvParam.ContextMenuStrip = cmsItem;
            }
            else
            {
                Text = Resources.JoinLocalizedString("Parameter", "Manager");
                lvParam.ContextMenuStrip = cmsList;
                if (Program.WinProperty.PropertyGrid.SelectedObjects != null &&
                    Program.WinProperty.PropertyGrid.SelectedObjects.All((object obj) =>
                {
                    return obj is BasicParameter;
                }))
                {
                    Program.WinProperty.PropertyGrid.SelectedObjects = null;
                    Program.WinProperty.Text = Resources.Translate("Property");
                }
            }
        }
        private void plus_Click(object sender, EventArgs e)
        {
            IncreaseSelectedParameter();
        }
        public void IncreaseSelectedParameter(int sign = 1)
        {
            foreach (ListViewItem item in lvParam.SelectedItems)
            {
                BasicParameter p = item.Tag as BasicParameter;
                p.Value.SetExpression(p.Value.Value + p.Step.Value * sign);
            }
            LinkedDocument.Modified = true;
        }
        private void minus_Click(object sender, EventArgs e)
        {
            IncreaseSelectedParameter(-1);
        }

        private void tsbResetRound_Click(object sender, EventArgs e)
        {
            ResetRound();
        }
        public void ResetRound()
        {
            foreach (ListViewItem item in lvParam.SelectedItems)
            {
                TwoStraightLinesArrivalAngleParameter p = item.Tag as TwoStraightLinesArrivalAngleParameter;
                if (p == null) continue;
                p.Round = 0;
                LinkedDocument.Modified = true;
            }
        }

        private void tsbDelete_EnabledChanged(object sender, EventArgs e)
        {
            Program.WinMain.NotifyMenuPropertyChanged("删除参数ToolStripMenuItem", nameof(ToolStripItem.Enabled), tsbDelete.Enabled);
        }

        private void plus_EnabledChanged(object sender, EventArgs e)
        {
            Program.WinMain.NotifyMenuPropertyChanged("参数自增ToolStripMenuItem", nameof(ToolStripItem.Enabled), plus.Enabled);
        }

        private void minus_EnabledChanged(object sender, EventArgs e)
        {
            Program.WinMain.NotifyMenuPropertyChanged("参数自减ToolStripMenuItem", nameof(ToolStripItem.Enabled), minus.Enabled);
        }

        private void tsbResetRound_EnabledChanged(object sender, EventArgs e)
        {
            Program.WinMain.NotifyMenuPropertyChanged("圈数归零ZToolStripMenuItem", nameof(ToolStripItem.Enabled), tsbResetRound.Enabled);
        }

        private void 添加参数NToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AddParameter();
        }

        private void 删除DToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DeleteParameters();
        }

        private void 自增ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            IncreaseSelectedParameter();
        }

        private void 自减ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            IncreaseSelectedParameter(-1);
        }

        private void 圈数归零ZToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ResetRound();
        }

        private void ParametersManagerWindow_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (e.CloseReason == CloseReason.UserClosing)
            {
                DockState = DockState.Hidden;
                e.Cancel = true;
            }
            Program.WinMain.ParameterManagerMenu.Checked = false;
        }
        public void SketchPad_Layer_RefreshWindowsStatus(LayerControl sender, LayerControl.RefreshWindowsStatusEventArgs e)
        {
            if (sender.SelectedItems.Count > 0)
            {
                //取消选中所有参数列表项
                foreach (ListViewItem item in lvParam.SelectedItems)
                {
                    item.Selected = false;
                }
            }
        }
        public void Parameter_Recovered(BasicParameter sender)
        {
            if (Program.WinDocuments.LinkedDocument == sender.Document)
            {
                lvParam.Items.Add(sender.ParametersManagerItem);
            }
        }

        private void tsbShowOtherParams_CheckedChanged(object sender, EventArgs e)
        {
            if (Settings.Instance.ShowOtherPadParameters = tsbShowOtherParams.Checked)
            {
                foreach (SketchPad pad in LinkedDocument.Pads)
                {
                    if (ReferenceEquals(pad, LinkedPad)) continue;
                    foreach (CalculatedParameter param in pad.Parameters)
                    {
                        if (param.ObjectState == ObjectState.Normal)
                        {
                            lvParam.Items.Add(param.ParametersManagerItem);
                        }
                    }
                }
            }
            else
            {
                foreach (SketchPad pad in LinkedDocument.Pads)
                {
                    if (ReferenceEquals(pad, LinkedPad)) continue;
                    foreach (CalculatedParameter param in pad.Parameters)
                    {
                        if (param.ObjectState == ObjectState.Normal)
                        {
                            param.ParametersManagerItem.Remove();
                        }
                    }
                }
            }
        }
    }
}
